<template>
  <div class="employees">
    <div class="app-container">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <!-- 头部 -->
        <template #header>
          <!-- 通栏组件 -->
          <PageTools>
            <template #left>
              <span>总计{{ total }}条数据</span>
            </template>
            <template #right>
              <el-button
                :loading="downloadLoading"
                type="primary"
                size="small"
                @click="$router.push('/import')"
              >
                导入excel
              </el-button>
              <el-button type="primary" size="small" @click="exportData">
                导出excel
              </el-button>
              <el-button
                v-if="canClick('p-em-add')"
                type="primary"
                size="small"
                @click="showDialog = true"
              >
                新增员工
              </el-button>
            </template>
          </PageTools>
        </template>
        <!-- body -->
        <div>
          <!-- table列表 -->
          <el-table
            border
            :data="list"
            :default-sort="{ prop: 'workNumber', order: 'descending' }"
          >
            <el-table-column type="index" label="序号" />
            <el-table-column prop="username" label="姓名" />
            <!-- 显示员工头像 -->
            <el-table-column label="头像">
              <template #default="{ row }">
                <el-image
                  class="staff"
                  :src="row.staffPhoto"
                  fit="cover"
                  @click="openCode(row.staffPhoto)"
                >
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="workNumber" label="工号" />
            <el-table-column label="聘用形式">
              <template #default="{ row }">
                {{ formOfEmployment(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column prop="departmentName" label="部门" />
            <el-table-column sortable prop="timeOfEntry" label="入职时间" />
            <el-table-column label="账户状态">
              <el-switch v-model="qy" />
            </el-table-column>
            <el-table-column
              fiexd="right"
              label="操作"
              fixed="right"
              width="280"
            >
              <template #default="{ row }">
                <el-button
                  v-if="canClick('p-em-look')"
                  type="text"
                  size="small"
                  @click="$router.push(`/employees/detail/${row.id}`)"
                >
                  查看
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="openAssignRole(row)"
                >
                  分配角色
                </el-button>
                <el-button
                  v-if="canClick('laowang-dele')"
                  type="text"
                  size="small"
                  @click="delEmploy(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <el-pagination
              background
              :page-sizes="[10, 2, 5]"
              :current-page="query.page"
              :total="total"
              :page-size="query.size"
              layout="prev, pager, next,sizes"
              @size-change="sizeChange"
              @current-change="changePage"
            />
          </el-row>
        </div>
      </el-card>
    </div>
    <!-- 弹层组件 -->
    <!-- <AddEmploy
      :show-dialog="showDialog"
      @close-dialog="showDialog = $event"
    ></AddEmploy> -->
    <AddEmploy :show-dialog.sync="showDialog" @refresh="getList"></AddEmploy>
    <!-- 二维码 -->
    <QrCode ref="qr" :show-code.sync="showCode"></QrCode>
    <!-- 给员工分配角色 -->
    <AssignRole
      ref="AssignRef"
      :show-role-dialog.sync="showRoleDialog"
    ></AssignRole>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees.js'
import dict from '@/api/constant/employees.js'
import AddEmploy from './components/add-Employee'
import QrCode from './components/qr-code'

// 分配角色弹出层
import AssignRole from './components/assign-role'
export default {
  components: {
    AddEmploy,
    QrCode,
    AssignRole
  },
  data () {
    return {
      showRoleDialog: false,
      // 头像弹层
      showCode: false,
      // 根据后台接口需要什么参数
      // 员工列表
      list: [],
      // 分页参数
      query: {
        page: 1,
        size: 10
      },
      // 员工总条数
      total: 0,
      qy: true,

      // 弹层显示控制
      showDialog: false,
      // loading 效果 for excel
      downloadLoading: false
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 打开分配角色弹框
    openAssignRole (row) {
      console.log(row)
      this.showRoleDialog = true
      this.$refs.AssignRef.getRoleDetailApi(row.id)
    },
    // 二维码弹层组件
    openCode (url) {
      this.showCode = true
      // 调用子组件中draw方法绘制二维码
      this.$refs.qr.draw(url)
    },
    // 导出某一页员工数据为 Excel下载保存到本地电脑
    async exportData () {
      // 开启 loading 开始导出
      this.downloadLoading = true
      const excel = await import('@/utils/Export2Excel')
      // console.log('模块导入方法', excel)
      // const header = ['Id', 'Title', 'Author', 'Readings', 'Date']
      // const data = []
      const { header, secondArray } = this.provideData()
      excel.export_json_to_excel({
        header, // 导出数据的表头
        data: secondArray, // 导出的具体数据(二维数组)
        filename: `第${this.query.page}页员工数据`, // 导出文件名
        autoWidth: true, // cell 宽度是否自适应
        bookType: 'xlsx' // 导出文件的格式
      })
      // 关闭loading 导出结束
      this.downloadLoading = false
    },
    // 准备要导出的 excel 数据方法
    provideData () {
      // 指定导出员工数据的映射关系
      const exportMap = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      // 表头
      const header = Object.keys(exportMap)
      // 指定导出的属性名
      const filterKeys = Object.values(exportMap)
      /**
       * 1. 准备一个空数组
       * 2.循环员工列表list，值存到二维数组里边
       * 3.返回处理完的二维数组
       */
      const secondArray = []
      this.list.forEach(item => {
        const userInfo = []
        for (const key in item) {
          if (filterKeys.includes(key)) {
            if (key === 'formOfEmployment') {
              userInfo.push(this.formOfEmployment(item[key]))
            } else {
              // 在映射关系中
              userInfo.push(item[key])
            }
          }
        }
        secondArray.push(userInfo)
      })
      return { header, secondArray }
    },
    // 删除员工
    async delEmploy (row) {
      // console.log(row)
      try {
        await this.$confirm('确认删除吗？')
        await delEmployee(row.id)
        // 处理最后一页数据全部删完后列表页码正确，数据显示有问题
        // 解决：重新计算页码 => 总页码 = (总数据-1)/每页的数据条数
        const newPage = Math.ceil(this.total - 1 / this.query.size)
        // console.log(newPage)
        if (this.query.page > newPage) {
          this.page = newPage
        }
        this.getList()
        this.$message.success('删除成功')
      } catch (error) {
        return error
      }
    },
    // 根据数组字典查询对应数字代表的含义 (码值)
    // type:1 正式 2非正式
    formOfEmployment (type) {
      // console.log('数据字典', dict)
      /*
        思路：
        1.生成映射关系 map:{1:'正式',2:'非正式'}
        2.根据map 获取对应玛值
       */
      const map = {}
      dict.hireType.forEach(item => {
        map[item.id] = item.value
      })
      // 返回根据map 获取到的码值，给模板渲染
      return map[type]
    },
    async getList () {
      const { rows, total } = await getEmployeeList(this.query)
      this.list = rows
      this.total = total
      // console.log(rows, total)
    },
    changePage (page) {
      console.log(page)
      this.query.page = page
      this.getList()
    },
    sizeChange (size) {
      console.log(size)
      this.query.size = size
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.staff {
  width: 70px;
  height: 70px;
  border-radius: 100%;
}
</style>
